package com.bainuo.doctor.common.image_support.imghandle.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;

import com.bainuo.doctor.common.R;
import com.bainuo.doctor.common.image_support.imghandle.Bean.ImageUploadInfo;
import com.bainuo.doctor.common.image_support.imghandle.ImageHandler;
import com.bainuo.doctor.common.image_support.imghandle.uploader.UploadTask;
import com.bainuo.doctor.common.network_engine.UpFileServerApi;
import com.bainuo.doctor.common.util.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by faraway on 15/2/17.
 */
public class ImagePickerView extends GridView {

    private Context context;

    private boolean isDisable;

    /**
     * gridview  adapter
     */
    private MyAdapter adapter = new MyAdapter();

    /**
     * GridView item 加载器
     */
    private PickerItemViewLoader[] pickerItemViewLoaders;

    /**
     * 加载器与任务id映射  用来作进度更新时方便更新视图
     */
    private Map<String, PickerItemViewLoader> mapLoader = new HashMap<>();

    /**
     * 选择图片文件信息数据
     */
    private List<ImageUploadInfo> imageInfos = new ArrayList<>();

    /**
     * 图片最大数量
     */
    private int maxCount = 9;

    public String uploadType;

    /**
     * 图片处理器
     */
    private ImageHandler imageHandler;


    public ImagePickerView(Context context) {
        super(context);
        init(context);
    }

    public ImagePickerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public void disable(boolean isDisable){
        this.isDisable = isDisable;
    }

    /**
     * 获取上传成功的图片集合
     *
     * @return
     */
    public List<ImageUploadInfo> getImages() {
        return imageInfos;
    }

    public void setUploadFileApi(UpFileServerApi api){
        if (imageHandler != null)
            imageHandler.setUploadFileApi(api);
    }

    public void setListImage(List<ImageUploadInfo> list){
        imageInfos.clear();
        imageInfos.addAll(list);
        adapter.notifyDataSetChanged(imageInfos);
    }

    /**
     * 初始化
     *
     * @param context
     */
    protected void init(final Context context) {

        this.context = context;

        //创建图片处理器
        imageHandler = new ImageHandler((Activity) context,null);
        imageHandler.imagePicker.setMaxPictures(maxCount);
//        imageHandler.autoUpload = false;

        //创建item加载器
        pickerItemViewLoaders = new PickerItemViewLoader[maxCount];
//        for (int i = 0; i < pickerItemViewLoaders.length; i++) {
//            final PickerItemViewLoader loader = new PickerItemViewLoader(context);
//            loader.index = i;
//
//            //设置删除item
//            loader.closeView.setOnClickListener(new OnClickListener() {
//                @Override
//                public void onClick(View v) {
//
//                    if (imageInfos.size() > loader.index) {
//
//                        //移除数据
//                        ImageUploadInfo info = imageInfos.remove(loader.index);
//                        //取消文件上传
//                        imageHandler.imageUpload.cancelRequest(info.id);
//                        mapLoader.remove(info.id);
//
//                        adapter.notifyDataSetChanged(imageInfos);
//
//                        if (listener != null) {
//                            listener.onImageDelete(imageInfos);
//                            if (isAllComplete())
//                                listener.onImagesUploadSuccess(imageInfos);
//                        }
//                    }
//                }
//            });
//
//            //重试上传
//            loader.retryView.setOnClickListener(new OnClickListener() {
//                @Override
//                public void onClick(View v) {
//
//                    if (imageInfos.size() > loader.index) {
//                        ImageUploadInfo info = imageInfos.get(loader.index);
////                        imageHandler.retry(info.getId());
//                        imageHandler.imageUpload.uploadFile(info);
//                        loader.setState(UploadTask.STATE_PRE);
//
//                        if (listener != null)
//                            listener.onImageUploadRetry(info);
//
//                    }
//                }
//            });
//            pickerItemViewLoaders[i] = loader;
//        }

        //设置图片处理器监听
        imageHandler.setImagHandlerListener(new ImageHandler.IImagHandlerListener() {

            @Override
            public void onPickerReult(boolean success, List<ImageUploadInfo> infos) {
                //图片上传成功后添加入数据
                imageInfos.addAll(infos);


                adapter.notifyDataSetChanged(imageInfos);

                if (listener != null)
                    listener.onImageSelected(infos);
            }

            @Override
            public void onImageCropReult(boolean success, ImageUploadInfo info) {
                if (uploadType == null)
                    info.setUploadType(UpFileServerApi.TYPE_DOCTOR);
                else
                    info.setUploadType(uploadType);
            }

            @Override
            public void onUploadResult(boolean state, ImageUploadInfo info) {

                //文件上传结果回调

                //获取loader
                PickerItemViewLoader loader = mapLoader.get(info.id);
                if (loader != null) {

                    //如果loader存在
                    if (state) {

                        //上传成功
                        loader.setState(info.STATE_COM);

                        if (listener != null) {
                            listener.onImageUploadSuccess(info);
                            //如果全部上传完成 则回调数据
                            if (isAllComplete()) {
                                listener.onImagesUploadSuccess(imageInfos);
                            }
                        }

                    } else {
                        //设置上传失败
                        loader.setState(info.STATE_FAILED);

                        if (listener != null)
                            listener.onImageUploadFailed(info);
                    }
                    //Log.e("1234555","success --->id:"+info.id+" load:"+loader+" ");
                    adapter.notifyDataSetChanged(imageInfos);
                }
            }


            @Override
            public void onUploadProgress(String id, int process) {

                //更新进度条
                PickerItemViewLoader loader = mapLoader.get(id);
                if (loader != null)
                    loader.setProgress(process);
            }
        });

        setAdapter(adapter);
    }

//    private PickerItemViewLoader getLoader(View view, final int postion){
//
//
//        if(view == null) {
//            PickerItemViewLoader loader = new PickerItemViewLoader(context);
//            view = loader.view;
//            view.setTag(loader);
//        }
//
//        final PickerItemViewLoader loader = (PickerItemViewLoader)view.getTag();
//
//
//        //设置删除item
//        loader.closeView.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                if (postion < imageInfos.size()) {
//
//                    //移除数据
//                    ImageUploadInfo info = imageInfos.remove(postion);
//                    //取消文件上传
//                    imageHandler.imageUpload.cancelRequest(info.id);
//                    mapLoader.remove(info.id);
//
//                    adapter.notifyDataSetChanged(imageInfos);
//
//                    if (listener != null) {
//                        listener.onImageDelete(imageInfos);
//                        if (isAllComplete())
//                            listener.onImagesUploadSuccess(imageInfos);
//                    }
//                }
//            }
//        });
//
//            //重试上传
//        loader.retryView.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                if (imageInfos.size() > postion) {
//                    ImageUploadInfo info = imageInfos.get(postion);
////                        imageHandler.retry(info.getId());
//                    imageHandler.imageUpload.uploadFile(info);
//                    loader.setState(UploadTask.STATE_PRE);
//
//                    if (listener != null)
//                        listener.onImageUploadRetry(info);
//
//                }
//            }
//        });
//
//        return loader;
//    }

    public void setResultCode(int imgCode, int cropCode) {
        if (imageHandler != null){
            if (imgCode != -1)
                imageHandler.setImageRequestCode(imgCode);
           if (cropCode != -1)
                imageHandler.cropRequestCode = cropCode;
        }
    }

    /**
     * 获取所有图片信息
     *
     * @return
     */
    public List<ImageUploadInfo> getImageInfos() {
        return imageInfos;
    }

    public boolean isAllComplete() {
        boolean complete = true;
        //检查是否全部任务完成
        for (ImageUploadInfo imgInfo : imageInfos) {
            if (!imgInfo.isUploadComplete()) {
                complete = false;
            }
        }

        return complete;
    }

    /**
     * 添加到图片数据映射中
     *
     * @param info
     * @param loader
     */
    private void addToMap(ImageUploadInfo info, PickerItemViewLoader loader) {

        String id = info.getId();

        if (loader.id != null && mapLoader.get(loader.id) == loader) {
            //如果之前这个loader 被使用过 则先移除 再进行添加
            mapLoader.remove(loader.id);
        }

        //如果loader没用被使用过则直接添加
        mapLoader.put(id, loader);
        loader.id = id;

    }

    /**
     * 设置最大数量
     *
     * @param maxCount
     */
    public void setMaxCount(int maxCount) {
        this.maxCount = maxCount;
        imageHandler.imagePicker.setMaxPictures(this.maxCount);
    }

    public void addImage(){
        imageHandler.imagePicker.setMaxPictures(maxCount - adapter.list.size());
        imageHandler.imagePicker.pickFromAlbum();
    }


    /**
     * gridview adapter
     */
    class MyAdapter extends BaseAdapter {

        public List<ImageUploadInfo> list = new ArrayList();

        public void notifyDataSetChanged(List<ImageUploadInfo> list) {
            this.list = list;//new ArrayList(list);
            super.notifyDataSetChanged();
        }

        @Override
        public int getCount() {

            //最大为 maxCount  小于 则返回文件数量加1  1为加号图片item
           int count =  Math.min(maxCount, list.size() +1);
           return isDisable?list.size():count;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }


        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {


            if(convertView == null || position == list.size()) {
                PickerItemViewLoader loader = new PickerItemViewLoader(context);
                convertView = loader.view;
                convertView.setTag(loader);
                //置空view 防止互相持有
                loader.view = null;
            }

            final PickerItemViewLoader loader = (PickerItemViewLoader)convertView.getTag();

//            PickerItemViewLoader loader = new PickerItemViewLoader(context);
//            convertView = loader.view;

            //设置删除item
            loader.closeView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (position < imageInfos.size()) {

                        //移除数据
                        ImageUploadInfo info = imageInfos.remove(position);
                        //取消文件上传
                        imageHandler.imageUpload.cancelRequest(info.id);
                        mapLoader.remove(info.id);

                        adapter.notifyDataSetChanged(imageInfos);

                        if (listener != null) {
                            listener.onImageDelete(imageInfos);
                            if (isAllComplete())
                                listener.onImagesUploadSuccess(imageInfos);
                        }
                    }
                }
            });

            //重试上传
            loader.retryView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (imageInfos.size() > position) {
                        ImageUploadInfo info = imageInfos.get(position);
//                        imageHandler.retry(info.getId());
                        imageHandler.imageUpload.uploadFile(info);
                        loader.setState(UploadTask.STATE_PRE);

                        if (listener != null)
                            listener.onImageUploadRetry(info);

                    }
                }
            });


//            //如果是最后一个item 则换为加号
            if (position == list.size()) {
//                loader.simpleDraweeView.setImageResource(R.mipmap.icon_tianjiatupian);

//                loader.simpleDraweeView.setImageURI("res://com.bainuo/"+R.mipmap.icon_tianjiatupian);

                loader.simpleDraweeView.setImageURI("res://com.bainuo/"+ R.mipmap.icon_tianjiatupian);

                //ImageLoader.setImage("http://img5.imgtn.bdimg.com/it/u=1511928397,1744182508&fm=26&gp=0.jpg",loader.simpleDraweeView);
                //修改为点击跳转相册
                loader.simpleDraweeView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean state = false;
                        if (listener != null) {
                            state = listener.onImageSelect();
                        }

                        if(!state){
                            addImage();
                        }
                    }
                });

                //加号不用映射任务id
//                if(mapLoader.get(loader.id) == loader )
//                      mapLoader.remove(loader.id);

                loader.reset();
            } else {

                //添加入map 方便更新进度
                ImageUploadInfo info = list.get(position);
                addToMap(info, loader);


                //展示图片
                if(info.getSrcPath().startsWith("http")){
                    ImageLoader.setImage(info.getSrcPath(),loader.simpleDraweeView);
                }else{
                    ImageLoader.setImage("file://"+info.getSrcPath(),loader.simpleDraweeView);
                }
                loader.simpleDraweeView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (listener != null)
                            listener.onImageClick(imageInfos,position);
                    }
                });

                //设置进度状态
                loader.setProgress(info.getProgress());
                loader.setState(info.getState());

                if (isDisable)
                    loader.closeView.setVisibility(GONE);

            }

            return convertView;
        }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        //防止视图在scroolview中两行以上不会撑开
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }

    /**
     * 获取图片上传器
     *
     * @return
     */
    public ImageHandler getImageHandler() {
        return imageHandler;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (imageHandler != null)
            imageHandler.onActivityResult(requestCode, resultCode, data);
    }


    IImagePickerViewListener listener;

    public void setImagePickViewListener(IImagePickerViewListener imagePickViewListener) {
        this.listener = imagePickViewListener;
    }

    public void onDestory(){

        if (imageHandler != null && imageHandler.imageUpload != null)
            imageHandler.imageUpload.cancelAllRequest();
    }

}
